package com.lkd.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.dto.VmDto;
import com.lkd.entity.Region;
import com.lkd.entity.VmType;
import com.lkd.mapper.*;
import com.lkd.result.PageBean;
import com.lkd.service.NodeService;
import com.lkd.service.VmService;
import com.lkd.vo.NodeVo;
import com.lkd.vo.VmVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VmServiceImpl implements VmService {
    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    @Autowired
    private VmTypeMapper vmTypeMapper;

    @Autowired
    private NodeService nodeService;

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<VmVo> findByNodeId(Long nodeId) {
        List<VmVo> vmVoList = vendingMachineMapper.findByNodeId(nodeId);
        vmVoList.stream().forEach(vmVo -> {
            //根据vmtype查询type信息
            VmType vmType = vmTypeMapper.findByTypeId(vmVo.getVmType());
            vmVo.setType(vmType);

            //根据nodeId查询type信息
            NodeVo nodeVo = nodeService.findById(vmVo.getNodeId());
            vmVo.setNode(nodeVo);

            //根据regionId查询type信息
            Region region = regionMapper.findById(vmVo.getRegionId());
            vmVo.setRegion(region);
        });
        return vmVoList;
    }

    @Autowired
    private VmMapper vmMapper;

    /**
     * 分页查询虚拟设备信息
     * @param vmDto 查询条件
     * @return 分页结果对象，包含查询到的虚拟设备信息
     */
    @Override
    public PageBean<VmVo> findByPage(VmDto vmDto) {
        // 1. 开始分页
        PageHelper.startPage(vmDto.getPageIndex(), vmDto.getPageSize());
        List<VmVo> list = vmMapper.findList(vmDto);
        // 遍历查询结果，补充设备类型、节点和区域信息
        list.stream().forEach(vmVo -> {
            // 补充设备类型信息
            VmType vmType = vmTypeMapper.findByTypeId(vmVo.getVmType());
            vmVo.setType(vmType);

            // 补充节点信息
            NodeVo nodeVo = nodeService.findById(vmVo.getNodeId());
            vmVo.setNode(nodeVo);

            // 补充区域信息
            Region region = regionMapper.findById(vmVo.getRegionId());
            vmVo.setRegion(region);
        });
        // 将补充完整的信息进行分页包装并返回
        Page<VmVo> p = (Page<VmVo>) list;
        return new PageBean(p.getPageNum(),p.getPageSize(),p.getTotal(),p.getPages(),p.getResult());
    }

}
